#!/usr/bin/env python
# -*- coding: utf-8 -*-

from string import Template
from tack.lib import string_app, content_headers, status_codes
from tack.lib.jsontools import json_dumps
from datetime import datetime

get_rank_sql = """
SELECT id, description, abbreviation
FROM ranks
ORDER BY id
"""

def build_row_dict(cd, row):
    d = {}
    for i, c in enumerate(row):
        if cd[i][1] == datetime:
            row[i] = row[i].strftime('%Y-%m-%d %H:%M:%S') if row[i] else None
        d[cd[i][0]] = row[i]
    return d

def get(environ, start_response):
    sql = Template(get_rank_sql).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    output = []
    for row in rows:
        row_dict = build_row_dict(cursor.description, row)
        output.append(row_dict) 
    output = json_dumps(output, indent=2)
    return string_app(output)(environ, start_response)